/**
 *
 */
package com.hefei.blog.web.controller.desk.posts;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hefei.blog.base.data.Data;
import com.hefei.blog.base.upload.consts.FileConsts;
import com.hefei.blog.base.utils.FileNameUtils;
import com.hefei.blog.base.utils.image.thread.ImageScaleExecutor;
import com.hefei.blog.base.utils.image.thread.ImageScaleThread;
import com.hefei.blog.core.biz.PostBiz;
import com.hefei.blog.core.data.Attach;
import com.hefei.blog.core.data.Group;
import com.hefei.blog.core.data.Post;
import com.hefei.blog.core.persist.service.AttachService;
import com.hefei.blog.core.persist.service.GroupService;
import com.hefei.blog.web.consts.Views;
import com.hefei.blog.web.controller.BaseController;
import com.hefei.frontend.framework.http.request.CommonParameterThreadLocal;
import com.hefei.frontend.framework.http.request.RequestThreadLocal;

/**
 * 文章操作
 * @author langhsu
 *
 */
@Controller
@RequestMapping("/post")
public class PostController extends BaseController {
	private static Logger log = Logger.getLogger(PostController.class);
	@Autowired
	private PostBiz postPlanet;
	@Autowired
	private GroupService groupService;
	@Autowired
	private AttachService attachService;

	/**
	 * 发布文章页
	 * @param groupKey
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/new/{groupKey}", method = RequestMethod.GET)
	public String view(@PathVariable String groupKey, ModelMap model) {
		Group group = groupService.getByKey(groupKey);
		model.put("group", group);
		return routeView(Views.ROUTE_POST_PUBLISH, group.getTemplate());
	}

	/**
	 * 提交发布
	 * @param blog
	 * @return
	 */
	@RequestMapping(value = "/submit", method = RequestMethod.POST)
	public String post(Post blog, HttpServletRequest request) {

		if (blog != null && StringUtils.isNotBlank(blog.getTitle())) {
//			UserProfile profile = getSubject(request);

			String[] ablums = request.getParameterValues("delayImages");
			blog.setAlbums(handleAlbums(ablums));
			blog.setAuthorId(CommonParameterThreadLocal.getUserId());

			postPlanet.post(blog);
		}
		return Views.REDIRECT_HOME_POSTS;
	}

	/**
	 * 删除文章
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete/{id}")
	public @ResponseBody Data delete(@PathVariable Long id, HttpServletRequest request) {
		Data data = Data.failure("操作失败");
		if (id != null) {
//			UserProfile up = getSubject(request);
			try {
				postPlanet.delete(id, CommonParameterThreadLocal.getUserId());
				data = Data.success("操作成功", Data.NOOP);
			} catch (Exception e) {
				log.error(RequestThreadLocal.getTimer() + " error", e);
				data = Data.failure(e.getMessage());
			}
		}
		return data;
	}

	/**
	 * 修改文章
	 * @param id
	 * @return
	 */
	@RequestMapping("/to_update/{id}")
	public String toUpdate(@PathVariable Long id, ModelMap model, HttpServletRequest request) {
//		UserProfile up = getSubject(request);
		Post ret = postPlanet.getPost(id);

		Assert.notNull(ret, "该文章已被删除");

		Assert.isTrue(ret.getAuthorId() == CommonParameterThreadLocal.getUserId(), "该文章不属于你");
		Group group = groupService.getById(ret.getGroup());

		model.put("view", ret);
		model.put("group", group);
		return routeView(Views.ROUTE_POST_UPDATE, group.getTemplate());
	}

	/**
	 * 更新文章方法
	 * @author LBB
	 * @return
	 */
	@RequestMapping(value = "/update/{groupKey}", method = RequestMethod.POST)
	public String subUpdate(Post p, HttpServletRequest request) {
//		UserProfile up = getSubject(request);
		if (p != null && p.getAuthorId() == CommonParameterThreadLocal.getUserId()) {
			String[] ablums = request.getParameterValues("delayImages");
			p.setAlbums(handleAlbums(ablums));
			postPlanet.update(p);
		}
		return Views.REDIRECT_HOME_POSTS;
	}

	@RequestMapping("/delete_album")
	public @ResponseBody Data deleteAlbum(Long id) {
		Data data = Data.failure("操作失败");
		if (id != null) {
			try {
				attachService.delete(id);
				data = Data.success("操作成功", Data.NOOP);
			} catch (Exception e) {
				log.error(RequestThreadLocal.getTimer() + " error", e);
				data = Data.failure(e.getMessage());
			}
		}
		return data;
	}


	protected List<Attach> handleAlbums(String[] albums) {
		if (albums == null || albums.length == 0) {
			return Collections.emptyList();
		}

		List<Attach> rets = new ArrayList<>();

		for (String album : albums) {
			if (StringUtils.isBlank(album)) {
				continue;
			}
			
//			String root = FileRepoFactory.getInstance().select().getRoot();
//			File temp = new File(root + album);
			Attach item = new Attach();
			try {
				// 保存原图
//				String orig = FileRepoFactory.getInstance().select().storeScale(temp, appContext.getOrigDir(), 750);
				item.setOriginal(album);

				// 创建缩放图片
				String preview =  FileNameUtils.getFilename(album, "305", "x");
				//FileRepoFactory.getInstance().select().storeScale(temp, appContext.getThumbsDir(), 305);
				ImageScaleExecutor.submit(new ImageScaleThread(FileConsts.ROOT_PIC + album, 305+"_x"));
				item.setPreview(preview);

				// 创建快照
				String screenshot = FileNameUtils.getFilename(album, "225", "140");
				ImageScaleExecutor.submit(new ImageScaleThread(FileConsts.ROOT_PIC + album, "225_140"));
						//FileRepoFactory.getInstance().select().storeScale(temp, appContext.getScreenshotDir(), 225, 140);
				item.setScreenshot(screenshot);

				rets.add(item);
			} catch (Exception e) {
				log.error(RequestThreadLocal.getTimer() + " error", e);
			}
		}

		return rets;
	}
}
